﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using HalconDotNet;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using Halcon二次开发.Model.自定义控件;
using Halcon二次开发.Tools;
using Halcon二次开发.View.角度界面;
namespace Halcon二次开发.Controller.角度合格检测
{
    public class AngleAction
    {
        /// <summary>
        /// 设置一条用于测量角度合格的基准线
        /// </summary>
        public HDrawingObject lineObjStandard;
        public HTuple[] attValuesStandard;
        //窗口句柄
        public HwindowFlowNodeUrseControl hwindowFlowNode;
        //窗口对象
        public AnagleForm pmaForm;
        /// <summary>
        /// 输入的行-列-角度 坐标
        /// </summary>
        public double[] HideIntputArrayRows, HideIntputArrayColumns, HideIntputArrayPhis;
        //输入图像
        public HObject HideIntputImage;

        //输出结果
        public List< bool> HideOutputResults;
        public AngleAction(HwindowFlowNodeUrseControl hwindowFlowNode, AnagleForm pmaForm)
        {
            this.hwindowFlowNode = hwindowFlowNode;
            this.pmaForm = pmaForm;
        }

        public AngleAction()
        {
        }

        public void Draw_StandardLine()
        {
            //create_metrology_model
            lineObjStandard = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, new HTuple[] { 0, 0, 100, 0 });

            //线段拖动触发事件注册
            lineObjStandard.OnDrag(LineOnDragStandard);
            //线段长度修改触发事件注册
            lineObjStandard.OnResize(LineOnResizeStandard);
            hwindowFlowNode.hSmartWindowControl1.HalconWindow.AttachDrawingObjectToWindow(lineObjStandard);

        }
        //线段拖动触发事件
        private void LineOnResizeStandard(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecData(drawid);
        }
        //线段长度修改事件
        private void LineOnDragStandard(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecData(drawid);
        }
        /// <summary>
        /// 线段拖动修改长度方法
        /// </summary>
        /// <param name="drawid"></param>
        public void UpdataDrawingObjecData(HDrawingObject drawid)
        {
            try
            {
                //创建一个要得到对象属性的元组
                var attTuple = new HTuple("row1", "column1", "row2", "column2");
                //获取对应的属性
                var valueTuple = drawid.GetDrawingObjectParams(attTuple);
                //对对应的属性进行封装一下,后面好加入到集合中
                attValuesStandard = new HTuple[] { valueTuple[0], valueTuple[1], valueTuple[2], valueTuple[3] };
                //算出与模板的差
                if (HideIntputArrayRows != null)
                {
                    if (HideIntputArrayRows.Length > 0)
                    {
                        pointStants = new List<double>();
                        //List中下标0，1是第一个点row和column的基准
                        //List中下标2是角度的基准
                        //List中下标3，4是第二个点row和column的基准
                        //计算偏移量 
                        pointStants.Add(attValuesStandard[0] - HideIntputArrayRows[SortRow(HideIntputArrayColumns)]);
                        pointStants.Add(attValuesStandard[1] - HideIntputArrayColumns[SortRow(HideIntputArrayColumns)]);
                        pointStants.Add(HideIntputArrayPhis[0]);
                        pointStants.Add(attValuesStandard[2] - HideIntputArrayRows[SortRow(HideIntputArrayColumns)]);
                        pointStants.Add(attValuesStandard[3] - HideIntputArrayColumns[SortRow(HideIntputArrayColumns)]);
                        //将这个基准数据进行保存
                        string path = $@"Data\工程文件\{hwindowFlowNode.name}工程文件\基准线保存文件";
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }
                        Directory.CreateDirectory(path);
                        //写入文件保存
                        HelpJsons.Write<double>(pointStants, path + "\\基准数据.json");
                    }
                }
            }
            catch (Exception ex)
            {
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置基准线失败，模板匹配工具设置基准线失败" + ":" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 找基准线方法开始
        /// </summary>
        //计量模型对象
        public HTuple hv_MetrologyHandle;
        //第一个点与第二个点的偏移量数据，这个需要保存
        //List中下标0，1是第一个点row和column的基准
        //List中下标2是角度的基准
        //List中下标3，4是第二个点row和column的基准
        public List<double> pointStants;

        public HObject lineHobject;
        //基准线对象  行坐标
        public HTuple startLineRows;
        //基准线对象 列坐标
        public HTuple startLineColumns;

        public void ReadFile()
        {
            string path = $@"Data\工程文件\{hwindowFlowNode.name}工程文件" + "\\基准线保存文件";
                if (pointStants == null)
                {
                    //读取基准数据
                    pointStants = HelpJsons.Read<double>(path + "\\基准数据.json");
                }
            if (attValuesCounterpoint == null)
            {
                List<double> line1Doubles = HelpJsons.Read<double>($@"Data\工程文件\{hwindowFlowNode.name}工程文件" + "\\对位线保存文件" + "\\线段数据.json");
                if (line1Doubles!=null)
                {
                    attValuesCounterpoint = new HTuple[] { line1Doubles[0], line1Doubles[1], line1Doubles[2], line1Doubles[3] };
                }
                
            }
            if (counterFrist == null)
            {
                counterFrist = HelpJsons.Read<double>($@"Data\工程文件\{hwindowFlowNode.name}工程文件" + "\\对位线保存文件" + "\\对位线数据.json");
            }
        }
        public void FindStandardLine()
        {
            try
            {
               
                //获取到模板的轮廓
                HOperatorSet.ReadShapeModel(pmaForm.shapeFilePath, out HTuple hv_ModelID2);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModeContours, hv_ModelID2, 1);
                //生成一个点
                HOperatorSet.GenCrossContourXld(out HObject Cross, 0, 0, 89, 60);
                //将模板仿射到我们的第一个模板的位置
                HOperatorSet.HomMat2dIdentity(out HTuple homMat2DIdentity);
                HOperatorSet.HomMat2dTranslate(homMat2DIdentity, HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homMat2DTranslate);
                HOperatorSet.HomMat2dRotate(homMat2DTranslate, HideIntputArrayPhis[SortRow(HideIntputArrayColumns)], HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homRotate);
                HOperatorSet.AffineTransContourXld(ho_ModeContours, out HObject contoursAffineTrans, homRotate);
                HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "green");
                //HOperatorSet.DispObj(contoursAffineTrans, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                //让模板轮廓进行跟随
                HOperatorSet.HomMat2dIdentity(out homMat2DIdentity);
                HOperatorSet.HomMat2dTranslate(homMat2DIdentity, HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homMat2DTranslate1);
                HOperatorSet.HomMat2dRotate(homMat2DTranslate1, -(pointStants[2] - HideIntputArrayPhis[SortRow(HideIntputArrayColumns)]), HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homMat2DRotate);
                //对第一个点进行仿射变换
                HOperatorSet.AffineTransPixel(homMat2DRotate, pointStants[0], pointStants[1], out HTuple poin1Trans1, out HTuple colTrans1);
                HOperatorSet.GenCrossContourXld(out HObject cross1, poin1Trans1, colTrans1, 89, 60);
                //对第二个点进行仿射变换
                HOperatorSet.AffineTransPixel(homMat2DRotate, pointStants[3], pointStants[4], out HTuple poin1Trans2, out HTuple colTrans2);
                HOperatorSet.GenCrossContourXld(out HObject cross2, poin1Trans2, colTrans2, 89, 60);
                //用2个点生成一条线
                HOperatorSet.GenRegionLine(out HObject regionLines, poin1Trans1, colTrans1, poin1Trans2, colTrans2);
                //创建计量模型，进行找线
                HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
                //增加一个矩形的计量模型
                double[] hTuple = new double[] { poin1Trans2, colTrans2, poin1Trans1, colTrans1 };
                HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", hTuple, (int)pmaForm.numericUpDown14.Value, (int)pmaForm.numericUpDown15.Value, 1, 2, new HTuple(), new HTuple(), out HTuple hv_Index);
                string polarity = "";
                if (pmaForm.comboBox5.SelectedItem.ToString() == "全部")
                {
                    polarity = "all";
                }
                if (pmaForm.comboBox5.SelectedItem.ToString() == "正极性")
                {
                    polarity = "negative";
                }
                if (pmaForm.comboBox5.SelectedItem.ToString() == "负极性")
                {
                    polarity = "positive";
                }
                if (pmaForm.comboBox5.SelectedItem.ToString() == "仅有")
                {
                    polarity = "uniform";
                }
                //设置极性
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
                //卡尺的数量
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", (int)pmaForm.numericUpDown11.Value);
                //卡尺卡的数量 接受的结果数
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
                //bilinear
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");

                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
                //最小分数
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(pmaForm.numericUpDown12.Value.ToString()));
                //开始抓
                HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);
                HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
                            out startLineRows, out startLineColumns);
                //将第一个点与最后的线进行生成，这样就可以获得一段基准线了
                HOperatorSet.GenRegionLine(out HObject contour, startLineRows[0], startLineColumns[0], startLineRows[startLineRows.Length - 1], startLineColumns[startLineColumns.Length - 1]);
                //contour这个线段对象就需要给到后面用了
                if (pmaForm.comboBox4.Text == "开启")
                {
                    HOperatorSet.DispObj(contour, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                    HOperatorSet.DispObj(ho_Contours, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                }
                if (lineObjStandard != null)
                {
                    //清除线段的显示
                    lineObjStandard.ClearDrawingObject();
                }
            }
            catch (Exception e)
            {
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText("基准线找取失败，请重新设置基准线" + ":" + e.Message + "\r\n");
            }
        }

        public void Tool_FindStandardLine()
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            hwindowFlowNode.hSmartWindowControl1.HalconWindow.ClearWindow();
            HOperatorSet.DispObj(HideIntputImage, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            FindStandardLine();
        }

        public int SortRow(double[] HideIntputArrayColumns )
        {
            //*以行排序tuple_sort(Row, Sorted)
            HOperatorSet.TupleSort(HideIntputArrayColumns, out HTuple sorted);
            int index = -1;
            for (int i = 0; i < sorted.Length; i++)
            {
                if (sorted[0] == HideIntputArrayColumns[i])
                {
                    index = i;
                    break;
                }
            }
            return index;
        }
        
        /// <summary>
        /// 对位线对象信息
        /// </summary>
        public HTuple[] attValuesCounterpoint;
        public HDrawingObject lineObjCounterpoint;
        /// <summary>
        /// 设置一条用于对位的线
        /// </summary>
        public void Draw_CounterpointLine()
        {
            lineObjCounterpoint = HDrawingObject.CreateDrawingObject(HDrawingObject.HDrawingObjectType.LINE, new HTuple[] { 100, 0, 300, 0 });
            //生成一个目标位置
            HOperatorSet.GenCircle(out HObject circle, HideIntputArrayRows[0], HideIntputArrayColumns[0], 20);
            HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "red");
            HOperatorSet.DispObj(circle, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            //线段拖动触发事件注册
            lineObjCounterpoint.OnDrag(LineOnDragCounterpoint);
            //线段长度修改触发事件注册
            lineObjCounterpoint.OnResize(LineOnResizeCounterpoint);
            hwindowFlowNode.hSmartWindowControl1.HalconWindow.AttachDrawingObjectToWindow(lineObjCounterpoint);
        }

        private void LineOnResizeCounterpoint(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecDataCounterpoint(drawid);
        }

        private void LineOnDragCounterpoint(HDrawingObject drawid, HWindow window, string type)
        {
            UpdataDrawingObjecDataCounterpoint(drawid);
        }
        //第一次模板的数据
        public List<double> counterFrist;
        private void UpdataDrawingObjecDataCounterpoint(HDrawingObject drawid)
        {
            try
            {
                try
                {
                    //创建一个要得到对象属性的元组
                    var attTuple = new HTuple("row1", "column1", "row2", "column2");
                    //获取对应的属性
                    var valueTuple = drawid.GetDrawingObjectParams(attTuple);
                    //对对应的属性进行封装一下,后面好加入到集合中
                    attValuesCounterpoint = new HTuple[] { valueTuple[0], valueTuple[1], valueTuple[2], valueTuple[3] };
                    counterFrist = new List<double>();
                    List<double> line1Doubles = new List<double>();
                    //记录第一次模板的位置
                    counterFrist.Add(HideIntputArrayRows[0]);
                    counterFrist.Add(HideIntputArrayColumns[0]);
                    counterFrist.Add(HideIntputArrayPhis[0]);
                    //保存线段数据
                    line1Doubles.Add(valueTuple[0]);
                    line1Doubles.Add(valueTuple[1]);
                    line1Doubles.Add(valueTuple[2]);
                    line1Doubles.Add(valueTuple[3]);
                    //将这个基准数据进行保存
                    //this.linestandarPath = filePath;
                    string path = $@"Data\工程文件\{hwindowFlowNode.name}工程文件\对位线保存文件";
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                    Directory.CreateDirectory(path);
                    HelpJsons.Write<double>(counterFrist, path + "\\对位线数据.json");
                    HelpJsons.Write<double>(line1Doubles, path + "\\线段数据.json");
                }
                catch (Exception ex)
                {
                    (FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置基准线失败，模板匹配工具设置基准线失败" + ":" + ex.Message + "\r\n");
                }
            }
            catch (Exception ex)
            {
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置基准线失败，模板匹配工具设置基准线失败" + ":" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 对位线的run方法
        /// </summary>

        public void FindCounterpointLine()
        {
            HideOutputResults = new List<bool>();
            if (lineObjCounterpoint != null)
            {
                hwindowFlowNode.hSmartWindowControl1.HalconWindow.DetachDrawingObjectFromWindow(lineObjCounterpoint);
                lineObjCounterpoint.Dispose();
                lineObjCounterpoint = null;
            }

            if (HideIntputArrayColumns != null)
            {
                try
                {
                    
                    //创建线的对象
                    HOperatorSet.GenRegionLine(out HObject hLine, attValuesCounterpoint[0], attValuesCounterpoint[1], attValuesCounterpoint[2], attValuesCounterpoint[3]);

                    for (int i = 0; i < HideIntputArrayColumns.Length; i++)
                    {
                        HObject ho_RegionAffineTrans = UtiyHalcon.MatrixCalculate(hLine, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], counterFrist[0], counterFrist[1], counterFrist[2]);
                        HOperatorSet.GetRegionPoints(ho_RegionAffineTrans, out HTuple hv_Rows, out HTuple hv_Columns);
                        if (hv_Rows.Length == 0)
                        {
                            continue;
                        }
                        //创建计量模型，进行找线
                        HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
                        //增加一个矩形的计量模型
                        double[] hTuple = new double[] { hv_Rows[0], hv_Columns[0], hv_Rows[hv_Rows.Length - 1], hv_Columns[hv_Columns.Length - 1] };

                        HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", hTuple, (int)pmaForm.numericUpDown17.Value, (int)pmaForm.numericUpDown16.Value, double.Parse(pmaForm.numericUpDown2.Value + ""), double.Parse(pmaForm.numericUpDown3.Value + ""), new HTuple(), new HTuple(), out HTuple hv_Index);
                        string polarity = "";
                        if (pmaForm.comboBox6.SelectedItem.ToString() == "全部")
                        {
                            polarity = "all";
                        }
                        if (pmaForm.comboBox6.SelectedItem.ToString() == "正极性")
                        {
                            polarity = "negative";
                        }
                        if (pmaForm.comboBox6.SelectedItem.ToString() == "负极性")
                        {
                            polarity = "positive";
                        }
                        if (pmaForm.comboBox6.SelectedItem.ToString() == "仅有")
                        {
                            polarity = "uniform";
                        }
                        //设置极性
                        HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
                        //卡尺的数量
                        HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", (int)pmaForm.numericUpDown19.Value);
                        //卡尺卡的数量 接受的结果数
                        HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
                        //bilinear
                        HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");

                        HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
                        //最小分数
                        HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(pmaForm.numericUpDown18.Value.ToString()));
                        //开始抓
                        HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);
                        HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
                                    out HTuple hv_Row, out HTuple hv_Column);
                        //将第一个点与最后的线进行生成，这样就可以获得一段基准线了
                        HOperatorSet.GenRegionLine(out HObject contour, hv_Row[0], hv_Column[0], hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1]);
                        //HOperatorSet.DispObj(ho_Contours, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                        //angle_ll(351.125, 483.702, 518.62, 836.118, 320.271, 765.635, 531.843, 536.564, Angle)
                        HOperatorSet.AngleLl(startLineRows[0], startLineColumns[0], startLineRows[startLineRows.Length - 1], startLineColumns[startLineColumns.Length - 1], hv_Row[0], hv_Column[0], hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1], out HTuple lineAngle);
                        double angle = new HTuple(lineAngle).TupleDeg();
                        //有角度给到我们的控件
                        if (i == 0)
                        {
                            pmaForm.numericUpDown20.Value = (decimal)angle;
                        }
                        double forwardAngle = (double)pmaForm.numericUpDown1.Value + (double)pmaForm.numericUpDown9.Value;
                        double lastAngle = (double)pmaForm.numericUpDown1.Value - (double)pmaForm.numericUpDown9.Value;
                        //角度合格就将截取的图片给到后面
                        if (angle <= (double)forwardAngle && angle >= (double)lastAngle)
                        {

                            //合格进行模板中心显示文本
                            HOperatorSet.SetTposition(hwindowFlowNode.hSmartWindowControl1.HalconWindow, HideIntputArrayRows[i] - 15, HideIntputArrayColumns[i] - 25);
                            //设置字体
                            HOperatorSet.SetFont(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "宋体" + "-Normal-" + 10);
                            //设置字体颜色
                            HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "green");
                            //contour这个线段对象就需要给到后面用了
                            if (pmaForm.comboBox4.Text == "开启")
                            {
                                HOperatorSet.DispObj(contour, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                            }
                            HOperatorSet.WriteString(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "角度:合格");
                            //记录合格数据
                            HideOutputResults.Add( true);
                            //合格不管
                        }
                        else
                        {
                            //合格进行模板中心显示文本
                            HOperatorSet.SetTposition(hwindowFlowNode.hSmartWindowControl1.HalconWindow, HideIntputArrayRows[i] - 15, HideIntputArrayColumns[i] - 25);
                            //设置字体
                            HOperatorSet.SetFont(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "宋体" + "-Normal-" + 10);
                            //设置字体颜色
                            HOperatorSet.SetColor(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "red");
                            //contour这个线段对象就需要给到后面用了
                            if (pmaForm.comboBox4.Text == "开启")
                            {
                                HOperatorSet.DispObj(contour, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                            }
                            HOperatorSet.WriteString(hwindowFlowNode.hSmartWindowControl1.HalconWindow, "角度:不合格");
                            //记录不合格数据
                            HideOutputResults.Add( false);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //(FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置对位线失败，模板匹配工具设置对位线失败" + ":" + ex.Message + "\r\n");
                    throw new Exception("设置对位线失败，模板匹配工具设置对位线失败" + ex.Message);
                }
            }
        }

        public void Tool_FindCounterpointLine()
        {
            if (HideIntputImage == null)
            {
                throw new Exception("当前图像为空");
            }
            hwindowFlowNode.hSmartWindowControl1.HalconWindow.ClearWindow();
            HOperatorSet.DispObj(HideIntputImage, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
            FindCounterpointLine();
        }

        public void Run()
        {

            //后加的进行角度是否合格功能,为0时开启角度合格功能，不是0正常走完流程
            if (pmaForm.comboBox1.Text=="打开")
            {
                //调用生成线
                FindStandardLine();
                //基准线的位置attValuesStandard
                if (pointStants != null)
                {
                    FindCounterpointLine();
                }
            }

        }
        /// <summary>
        /// 硬触发run方法
        /// </summary>
        public void HardRun(AnagleForm pmaForm, HSmartWindowControl hSmartWindowControl, HTuple startLineRows, HTuple startLineColumns, HObject HideIntputImage, List<double> pointStants, double[] HideIntputArrayRows, double[] HideIntputArrayColumns, double[] HideIntputArrayPhis,ref List<bool> HideOutputResults,HTuple[] attValuesCounterpoint, List<double> counterFrist,ref double angle)
        {
            try
            {
                //获取到模板的轮廓
                HOperatorSet.ReadShapeModel(pmaForm.shapeFilePath, out HTuple hv_ModelID2);
                HOperatorSet.GetShapeModelContours(out HObject ho_ModeContours, hv_ModelID2, 1);
                //生成一个点
                HOperatorSet.GenCrossContourXld(out HObject Cross, 0, 0, 89, 60);
                //将模板仿射到我们的第一个模板的位置
                HOperatorSet.HomMat2dIdentity(out HTuple homMat2DIdentity);
                HOperatorSet.HomMat2dTranslate(homMat2DIdentity, HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homMat2DTranslate);
                HOperatorSet.HomMat2dRotate(homMat2DTranslate, HideIntputArrayPhis[SortRow(HideIntputArrayColumns)], HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homRotate);
                HOperatorSet.AffineTransContourXld(ho_ModeContours, out HObject contoursAffineTrans, homRotate);
                HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "green");
                //HOperatorSet.DispObj(contoursAffineTrans, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                //让模板轮廓进行跟随
                HOperatorSet.HomMat2dIdentity(out homMat2DIdentity);
                HOperatorSet.HomMat2dTranslate(homMat2DIdentity, HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homMat2DTranslate1);
                HOperatorSet.HomMat2dRotate(homMat2DTranslate1, -(pointStants[2] - HideIntputArrayPhis[SortRow(HideIntputArrayColumns)]), HideIntputArrayRows[SortRow(HideIntputArrayColumns)], HideIntputArrayColumns[SortRow(HideIntputArrayColumns)], out HTuple homMat2DRotate);
                //对第一个点进行仿射变换
                HOperatorSet.AffineTransPixel(homMat2DRotate, pointStants[0], pointStants[1], out HTuple poin1Trans1, out HTuple colTrans1);
                HOperatorSet.GenCrossContourXld(out HObject cross1, poin1Trans1, colTrans1, 89, 60);
                //对第二个点进行仿射变换
                HOperatorSet.AffineTransPixel(homMat2DRotate, pointStants[3], pointStants[4], out HTuple poin1Trans2, out HTuple colTrans2);
                HOperatorSet.GenCrossContourXld(out HObject cross2, poin1Trans2, colTrans2, 89, 60);
                //用2个点生成一条线
                HOperatorSet.GenRegionLine(out HObject regionLines, poin1Trans1, colTrans1, poin1Trans2, colTrans2);
                //创建计量模型，进行找线
                HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
                
                //增加一个矩形的计量模型
                double[] hTuple = new double[] { poin1Trans2, colTrans2, poin1Trans1, colTrans1 };
                HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", hTuple, (int)pmaForm.numericUpDown14.Value, (int)pmaForm.numericUpDown15.Value, 1, 2, new HTuple(), new HTuple(), out HTuple hv_Index);
                string polarity = "";
                if (pmaForm.comboBox5.SelectedItem.ToString() == "全部")
                {
                    polarity = "all";
                }
                if (pmaForm.comboBox5.SelectedItem.ToString() == "正极性")
                {
                    polarity = "negative";
                }
                if (pmaForm.comboBox5.SelectedItem.ToString() == "负极性")
                {
                    polarity = "positive";
                }
                if (pmaForm.comboBox5.SelectedItem.ToString() == "仅有")
                {
                    polarity = "uniform";
                }
                //设置极性
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
                //卡尺的数量
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", (int)pmaForm.numericUpDown11.Value);
                //卡尺卡的数量 接受的结果数
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
                //bilinear
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");

                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
                //最小分数
                HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(pmaForm.numericUpDown12.Value.ToString()));
                //开始抓
                HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);
                HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
                            out startLineRows, out startLineColumns);
                //将第一个点与最后的线进行生成，这样就可以获得一段基准线了
                HOperatorSet.GenRegionLine(out HObject contour, startLineRows[0], startLineColumns[0], startLineRows[startLineRows.Length - 1], startLineColumns[startLineColumns.Length - 1]);
                //contour这个线段对象就需要给到后面用了
                if (pmaForm.comboBox4.Text == "开启")
                {
                    HOperatorSet.DispObj(contour, hSmartWindowControl.HalconWindow);
                    HOperatorSet.DispObj(ho_Contours, hSmartWindowControl.HalconWindow);
                }
            }
            catch (Exception e)
            {
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText("基准线找取失败，请重新设置基准线" + ":" + e.Message + "\r\n");
            }
            if (pointStants != null)
            {
                HideOutputResults = new List<bool>();

                if (HideIntputArrayColumns != null)
                {
                    try
                    {

                        //创建线的对象
                        HOperatorSet.GenRegionLine(out HObject hLine, attValuesCounterpoint[0], attValuesCounterpoint[1], attValuesCounterpoint[2], attValuesCounterpoint[3]);

                        for (int i = 0; i < HideIntputArrayColumns.Length; i++)
                        {
                            HObject ho_RegionAffineTrans = UtiyHalcon.MatrixCalculate(hLine, HideIntputArrayRows[i], HideIntputArrayColumns[i], HideIntputArrayPhis[i], counterFrist[0], counterFrist[1], counterFrist[2]);
                            HOperatorSet.GetRegionPoints(ho_RegionAffineTrans, out HTuple hv_Rows, out HTuple hv_Columns);
                            if (hv_Rows.Length == 0)
                            {
                                continue;
                            }
                            //创建计量模型，进行找线
                            HOperatorSet.CreateMetrologyModel(out HTuple hv_MetrologyHandle);
                            //增加一个矩形的计量模型
                            double[] hTuple = new double[] { hv_Rows[0], hv_Columns[0], hv_Rows[hv_Rows.Length - 1], hv_Columns[hv_Columns.Length - 1] };

                            HOperatorSet.AddMetrologyObjectGeneric(hv_MetrologyHandle, "line", hTuple, (int)pmaForm.numericUpDown17.Value, (int)pmaForm.numericUpDown16.Value, double.Parse(pmaForm.numericUpDown2.Value + ""), double.Parse(pmaForm.numericUpDown3.Value + ""), new HTuple(), new HTuple(), out HTuple hv_Index);
                            string polarity = "";
                            if (pmaForm.comboBox6.SelectedItem.ToString() == "全部")
                            {
                                polarity = "all";
                            }
                            if (pmaForm.comboBox6.SelectedItem.ToString() == "正极性")
                            {
                                polarity = "negative";
                            }
                            if (pmaForm.comboBox6.SelectedItem.ToString() == "负极性")
                            {
                                polarity = "positive";
                            }
                            if (pmaForm.comboBox6.SelectedItem.ToString() == "仅有")
                            {
                                polarity = "uniform";
                            }
                            //设置极性
                            HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_transition", polarity);
                            //卡尺的数量
                            HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_measures", (int)pmaForm.numericUpDown19.Value);
                            //卡尺卡的数量 接受的结果数
                            HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "num_instances", 1);
                            //bilinear
                            HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_interpolation", "bicubic");

                            HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "measure_select", "all");
                            //最小分数
                            HOperatorSet.SetMetrologyObjectParam(hv_MetrologyHandle, "all", "min_score", double.Parse(pmaForm.numericUpDown18.Value.ToString()));
                            //开始抓
                            HOperatorSet.ApplyMetrologyModel(HideIntputImage, hv_MetrologyHandle);
                            HOperatorSet.GetMetrologyObjectMeasures(out HObject ho_Contours, hv_MetrologyHandle, "all", "all",
                                        out HTuple hv_Row, out HTuple hv_Column);
                            //将第一个点与最后的线进行生成，这样就可以获得一段基准线了
                            HOperatorSet.GenRegionLine(out HObject contour, hv_Row[0], hv_Column[0], hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1]);
                            //HOperatorSet.DispObj(ho_Contours, hwindowFlowNode.hSmartWindowControl1.HalconWindow);
                            //angle_ll(351.125, 483.702, 518.62, 836.118, 320.271, 765.635, 531.843, 536.564, Angle)
                            HOperatorSet.AngleLl(startLineRows[0], startLineColumns[0], startLineRows[startLineRows.Length - 1], startLineColumns[startLineColumns.Length - 1], hv_Row[0], hv_Column[0], hv_Row[hv_Row.Length - 1], hv_Column[hv_Column.Length - 1], out HTuple lineAngle);
                             angle = new HTuple(lineAngle).TupleDeg();
                            ////有角度给到我们的控件
                            //if (i == 0)
                            //{
                            //    pmaForm.numericUpDown20.Value = (decimal)angle;
                            //}
                            double forwardAngle = (double)pmaForm.numericUpDown1.Value + (double)pmaForm.numericUpDown9.Value;
                            double lastAngle = (double)pmaForm.numericUpDown1.Value - (double)pmaForm.numericUpDown9.Value;
                            //角度合格就将截取的图片给到后面
                            if (angle <= (double)forwardAngle && angle >= (double)lastAngle)
                            {

                                //合格进行模板中心显示文本
                                HOperatorSet.SetTposition(hSmartWindowControl.HalconWindow, HideIntputArrayRows[i] - 15, HideIntputArrayColumns[i] - 25);
                                //设置字体
                                HOperatorSet.SetFont(hSmartWindowControl.HalconWindow, "宋体" + "-Normal-" + 10);
                                //设置字体颜色
                                HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "green");
                                //contour这个线段对象就需要给到后面用了
                                if (pmaForm.comboBox4.Text == "开启")
                                {
                                    HOperatorSet.DispObj(contour, hSmartWindowControl.HalconWindow);
                                }
                                HOperatorSet.WriteString(hSmartWindowControl.HalconWindow, "角度:合格");
                                //记录合格数据
                                HideOutputResults.Add(true);
                                //合格不管
                            }
                            else
                            {
                                //合格进行模板中心显示文本
                                HOperatorSet.SetTposition(hSmartWindowControl.HalconWindow, HideIntputArrayRows[i] - 15, HideIntputArrayColumns[i] - 25);
                                //设置字体
                                HOperatorSet.SetFont(hSmartWindowControl.HalconWindow, "宋体" + "-Normal-" + 10);
                                //设置字体颜色
                                HOperatorSet.SetColor(hSmartWindowControl.HalconWindow, "red");
                                //contour这个线段对象就需要给到后面用了
                                if (pmaForm.comboBox4.Text == "开启")
                                {
                                    HOperatorSet.DispObj(contour, hSmartWindowControl.HalconWindow);
                                }
                                HOperatorSet.WriteString(hSmartWindowControl.HalconWindow, "角度:不合格");
                                //记录不合格数据
                                HideOutputResults.Add(false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //(FormDb.Db["Form1"] as Form1).textBox1.AppendText("设置对位线失败，模板匹配工具设置对位线失败" + ":" + ex.Message + "\r\n");
                        throw new Exception("设置对位线失败，模板匹配工具设置对位线失败" + ex.Message);
                    }
                }
            }
        }

    }
}
